package max.ubitest.pipe.view
{
	import max.ubitest.pipe.Config;
	import max.ubitest.pipe.data.CellData;
	import max.ubitest.pipe.data.ComponentTypes;
	import max.ubitest.pipe.locators.ComponentsLocator;
	
	import mx.events.CollectionEvent;
	import mx.events.CollectionEventKind;
	
	import org.robotlegs.mvcs.Mediator;
	
	public class CompContainerMediator extends Mediator
	{
		[Inject]
		public var view:CompContainer;
		[Inject]
		public var locator:ComponentsLocator;
		
		public function CompContainerMediator()
		{
			super();
		}
		
		override public function onRegister():void{
			eventMap.mapListener(locator.mappedComponents, CollectionEvent.COLLECTION_CHANGE, onChange);
		}
		
		override public function preRemove():void{
			eventMap.unmapListener(locator.mappedComponents, CollectionEvent.COLLECTION_CHANGE, onChange);
		}
		
		private function onChange(e:CollectionEvent):void{
			if(e.kind == CollectionEventKind.ADD){
				addComponents(e.items);
			}else if(e.kind == CollectionEventKind.REMOVE){
				removeComponents(e.items);
			}
		}
		
		private function addComponents(items:Array):void{
			var render:ComponentRenderer;
			for each(var cell:CellData in items){
				render = new ComponentRenderer();
				render.data = cell.componentData;
				render.x = cell.x * Config.CELL_SIZE;
				render.y = cell.y * Config.CELL_SIZE;
				render.width  = cell.componentData.width * Config.CELL_SIZE;
				render.height = cell.componentData.height * Config.CELL_SIZE;
				
				if(cell.componentData.type == ComponentTypes.RESERVOIR){
					render.x -= Config.CELL_SIZE;
					render.y -= Config.CELL_SIZE;
				}
				
				view.addElement(render);
			}
		}
		
		private function removeComponents(items:Array):void{
			var render:ComponentRenderer;
			for each(var item:CellData in items){
				for(var i:int = 0;i<view.numChildren;i++){
					render = view.getElementAt(i) as ComponentRenderer;
					if(render.data == item.componentData){
						view.removeElement(render);
					}
				}
			}
		}
	}
}